<script setup>
import {
  ElMessage, ElForm, ElFormItem, ElSelect, ElOption, ElButton, ElInput,
} from 'element-plus';
import { nextTick, ref, computed } from 'vue';
import cyber from '../../../lib/cybercloud';

const props = defineProps({
  tableConfig: {
    type: Object,
    default() {
      return {};
    },
  },
  selectForm: {
    type: Object,
    default() {
      return {};
    },
  },
  enums: {
    type: Object,
    default() {
      return {};
    },
  },
});
const emit = defineEmits(['getCheckboxRecords', 'update:selectForm']);
const fetchMode = ref('page-loading');
const fetchOptions = ref({ immediate: false });
const selectForm = computed({
  get() {
    return props.selectForm;
  },
  set(d) {
    emit('update:selectForm', d);
  },
});
const data = ref([]);

let total = ref(0);
const pageSize = ref(50);
const pageTable = ref(null);

function remoteMethod(query, name, urlAdd, methodType, params, index, attribute) {
  selectForm.value.items[index].options.loading = true;
  if (query && params.filters && params.filters.length > 0) {
    params.filters[0].value = query;
  }
  cyber.request({
    method: methodType,
    url: urlAdd,
    data: params,
  })
    .then((response) => {
      if (response.success) {
        const list = response.data.objects;
        const optionsList = [];
        Object.values(list)
          .forEach((item) => {
            const option = {
              label: '',
              value: '',
            };
            Object.keys(item)
              .forEach((attr) => {
                if (attribute.label === attr) {
                  option.label = item[attr];
                }
                if (attribute.value === attr) {
                  option.value = item[attr];
                }
                if (attribute.code === attr) {
                  option.code = item[attr];
                }
              });
            if (option.label && option.value) {
              optionsList.push(option);
            }
          });
        selectForm.value
          .items[index].selectRemote.optionsData.data = optionsList;
      }
      selectForm.value.items[index].options.loading = false;
    })
    .catch(() => ElMessage.error('操作失败'));
}

function resetFields() {
  Object.values(props.selectForm.items)
    .forEach((item) => {
      item.value = '';
    });
}

const fetchHandler = ref((params) => new Promise(((resolve) => {
  Object.keys(props.tableConfig.fetchParams)
    .forEach((key) => {
      if (key === 'objectId') {
        params.objectId = props.tableConfig.fetchParams.objectId;
      } else if (key === 'filters') {
        params.filters = [];
        Object.values(props.selectForm.items)
          .forEach((item) => {
            if (item.value) {
              Object.values(props.tableConfig.fetchParams.filters)
                .forEach((filter) => {
                  if (filter.code === item.code) {
                    filter.value = item.value;
                    params.filters.push(filter);
                  }
                });
            }
          });
      }
    });
  params.offset = (params.pageIndex - 1) * params.pageSize;
  cyber.request({
    method: 'POST',
    url: '/api/app/corm/list',
    data: params,
  })
    .then((response) => {
      if (response.success) {
        const resultList = response.data.objects;
        total = response.data.totalCount;
        const {
          conversionEnum,
        } = props.tableConfig;
        // 数据转化
        Object.values(resultList)
          .forEach((item) => {
            Object.keys(item).forEach((itemKey) => {
              if (item[itemKey] instanceof Object) {
                const attributes = item[itemKey].displayFields; // displayFields 平台固定关联对象名
                const arr = [];
                Object.values(attributes)
                  .forEach((obj) => {
                    arr.push(obj.value);
                  });
                item[itemKey] = arr.join(',');
              }
            });
            Object.keys(conversionEnum)
              .forEach((key) => {
                if (item[key] !== undefined && item[key] !== '') {
                  const enumList = props.enums[key] !== undefined ? props.enums[key] : [];
                  Object.values(enumList)
                    .forEach((enumTemp) => {
                      if (enumTemp.value === item[key]) {
                        item[key] = enumTemp.label;
                      }
                    });
                }
              });
          });
        resolve({
          objects: resultList,
          hasMoreResults: response.data.hasMoreResults,
          totalCount: total,
        });
      } else {
        ElMessage.error(response.data.message);
        resolve({
          objects: [],
          hasMoreResults: false,
          totalCount: 0,
        });
      }
    })
    .catch(() => {
      ElMessage.error('列表获取失败');
      resolve({
        objects: [],
        hasMoreResults: false,
        totalCount: 0,
      });
    });
})));

function getCheckboxRecords() {
  const checkBox = pageTable.value.call('getCheckboxRecords');
  emit('getCheckboxRecords', checkBox);
}

function reload() {
  pageTable.value.reload();
  nextTick(() => {
    getCheckboxRecords();
  });
}

defineExpose({
  reload,
});
</script>
<template>
  <el-form ref="selectForm" :model="selectForm"
           :label-position="selectForm.labelPosition"
           :size="selectForm.size"
           :label-width="selectForm.labelWidth"
  >
    <div class="selectForm">
      <div v-for="(item,index) of selectForm.items" :key="index">
        <el-form-item :label="item.name">
          <el-input v-if="item.type === 'input'" :style="item.options.style"
                    :placeholder="item.options.placeholder"
                    v-model="item.value"
          />
          <el-select v-else-if="item.type === 'selectRemote'"
                     :ref="'tableSelectRemote_'+index"
                     :style="item.options.style"
                     filterable
                     :loading="item.options.loading"
                     remote
                     :clearable="true"
                     reserve-keyword
                     :placeholder="item.options.placeholder"
                     :remote-method="(query) =>
                               remoteMethod(query,
                                    'tableSelectRemote_'+index,
                                    item.selectRemote.url,
                                    item.selectRemote.method,
                                    item.selectRemote.params,
                                    index,
                                    item.selectRemote.optionsData.attribute
                                    )"
                     v-model="item.value">
            <el-option
              v-for="optionTemp in item.selectRemote.optionsData.data"
              :key="optionTemp.value"
              :label="optionTemp.label"
              :value="optionTemp.value">
              <span style="float: left">{{ optionTemp.code }}</span>
              <span style=" float: right;
                        color: var(--el-text-color-secondary);
                        font-size: 13px;"
              >{{ optionTemp.label }}</span
              >
            </el-option>
          </el-select>

          <el-select v-else-if="item.type === 'select'"
                     :style="item.options.style"
                     :ref="'formSelect_'+index"
                     :placeholder="item.options.placeholder"
                     :clearable="true"
                     v-model="item.value"
          >
            <el-option
              v-for="optionTemp in
                       enums[item.enumsName] !== undefined ?enums[item.enumsName]:[] "
              :key="optionTemp.value"
              :label="optionTemp.label"
              :value="optionTemp.value">
            </el-option>
          </el-select>

        </el-form-item>
      </div>
    </div>
  </el-form>
  <div class="selectButton">
    <el-button size="small" type="primary" @click="reload">搜索</el-button>
    <el-button size="small" @click="resetFields">重置</el-button>
  </div>
  <div class="tableDiv">
    <c-table ref="pageTable" v-model:data="data"
             :header-cell-style="{'text-align':'left'}"
             :cell-style="{'text-align':'left'}"
             :fetchOptions="fetchOptions"
             :fetchMode="fetchMode"
             :columns='tableConfig.columns'
             :fetchHandler='fetchHandler'
             :pageSize="pageSize"
             height="auto"
             @checkboxChange="getCheckboxRecords"
             @checkboxAll="getCheckboxRecords"
             style="width: 100%;"
    >
      <template #code="scope">
        <router-link
          :to="tableConfig.routerLink+'?' +
                  'entity_id='+scope.row.id+'&objectId=location'">
          {{scope.row.code}}
        </router-link>
      </template>
    </c-table>
  </div>
</template>
<style scoped lang="sass">
@import "PageTable.sass"
</style>
